/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-11-06
 * Time:15:47
 */
public class HashBuck {
    static class Node{
        public int key;
        public int val;
        Node next;
        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[]array;
    public int useSize;
    public HashBuck(){
        array=new Node[8];
    }
    public void put(int key,int val){
        int index=key% array.length;
        //遍历看看里面有没有，有的话需要替换
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
            }
            cur=cur.next;
        }
        //头插法
        Node node=new Node(key,val);
        node.next=array[index];
        array[index]=node;
        useSize++;
        //负载因子不能超过0.75
        if(loadFactor()>=0.75f){
            resize();
        }
    }
    private void resize(){
        Node[]newArray=new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur=array[i];
            while(cur!=null){
                //Node curNext=cur.next;
                int newIndex=cur.key% newArray.length;
                Node newNode=new Node(cur.key,cur.val);
                newNode.next=newArray[newIndex];
                newArray[newIndex]=newNode;
                cur=cur.next;
            }
        }
        array=newArray;
    }
    private float loadFactor(){
        return useSize*1.0f/array.length;
    }
    public int put(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
    //写一个泛型
    //自定义类型重写的都重写一遍
}
